package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("zuul过滤器开始...");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if(request.getMethod().equals("OPTIONS")){
            System.out.println("222");
            return null;
        }
        String url = request.getRequestURI().toString();
        if(url.indexOf("/admin/login")>0){
            System.out.println("登陆页面"+url);
            return null;
        }
        String authorization = request.getHeader("Authorization");
        System.out.println("authorization = " + authorization);
        if(authorization!=null&&authorization.startsWith("Bearer ")){
            String token = authorization.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            System.out.println("claims = " + claims);
            if(claims!=null){
                String roles = (String) claims.get("roles");
                System.out.println("roles = " + roles);
                if(roles.equals("admin")){
                    currentContext.addZuulRequestHeader("Authorization",authorization);
                    System.out.println("token 验证通过，添加了头信息"+authorization);
                    return null;
                }
            }
        }
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(401);
        currentContext.setResponseBody("无权访问");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
